package TotalPage

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
)

//计算分页总数
type TotalPage struct {
	controllers.MainController
}

//文章总数
type CountPage struct {
	Id int
}

func (this *TotalPage) Get() {
	keyword := this.GetString("keyword")
	category := this.GetString("category")      //获取文章类别
	pagecount, err1 := this.GetInt("pagecount") //获取一页的数据列数量
	if err1 != nil {
		body := map[string]interface{}{"code": 300, "totalpage": 0}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	db := models.ConnDb()
	defer db.Close()
	var c CountPage
	//如果是查询
	if keyword != "" {
		//将相应类别的文章展示
		sql := "select count(blog_id) as id from tbloginfo where blog_title or blog_content like '%" + keyword + "%' and is_deleted = 0;"
		err2 := db.Raw(sql).Scan(&c).Error
		if err2 != nil {
			body := map[string]interface{}{"code": 301, "totalpage": 0}
			this.Data["json"] = body
			this.ServeJSON()
			return
		}
		var total int
		if c.Id%10 != 0 {
			total = c.Id/pagecount + 1
		} else {
			total = c.Id / pagecount
		}
		body := map[string]interface{}{"code": 200, "totalpage": total}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}

	//如果是主页
	if category == "Home" {
		//将相应类别的文章展示
		err2 := db.Raw("select count(blog_id) as id from tbloginfo where is_deleted=0;").Scan(&c).Error
		if err2 != nil {
			body := map[string]interface{}{"code": 302, "totalpage": 0}
			this.Data["json"] = body
			this.ServeJSON()
			return
		}
		var total int
		if c.Id%10 != 0 {
			total = c.Id/pagecount + 1
		} else {
			total = c.Id / pagecount
		}
		body := map[string]interface{}{"code": 200, "totalpage": total}
		this.Data["json"] = body
		this.ServeJSON()
		return
	} else {
		//将相应类别的文章展示
		err3 := db.Raw("select count(blog_id) as id from tbloginfo where category=? and is deleted=0;", category).Scan(&c).Error
		if err3 != nil {
			body := map[string]interface{}{"code": 303, "totalpage": 0}
			this.Data["json"] = body
			this.ServeJSON()
			return
		}
		var total int
		if c.Id%10 != 0 {
			total = c.Id/pagecount + 1
		} else {
			total = c.Id / pagecount
		}
		body := map[string]interface{}{"code": 200, "totalpage": total}
		this.Data["json"] = body
		this.ServeJSON()
	}
}
